package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.entity.Employee;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 自定义切面
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {

    // 切入点
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill))")
    public void autoFillPointCut() {
    }

    /**
     * 前置通知， 公共字段赋值
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint jP) {
        log.info("开始公共字段填充");

        // 获取操作类型
        MethodSignature signature = (MethodSignature) jP.getSignature();
        AutoFill fill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = fill.value();

        // 获取实体对象
        Object[] args = jP.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object obj = args[0];

        // 准备数据
        LocalDateTime now = LocalDateTime.now();
        long currentId = BaseContext.getCurrentId();
        // 反射，设置属性

        if (operationType == OperationType.INSERT) {
            try {
                Method setCreateTime = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateTime = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setCreateTime.invoke(obj, now);
                setCreateUser.invoke(obj, currentId);
                setUpdateTime.invoke(obj, now);
                setUpdateUser.invoke(obj, currentId);

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (operationType == OperationType.UPDATE) {
            try {
                Method setUpdateTime = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = obj.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setUpdateTime.invoke(obj, now);
                setUpdateUser.invoke(obj, currentId);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

}
